<template>
  <div v-if="goodsDetail">
    <van-nav-bar
      :title="goodsDetail.proname"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 轮播图 -->
    <van-swipe :autoplay="3000" indicator-color="white" class="swipe">
      <van-swipe-item
        v-for="(item, index) in goodsDetail.banners[0].split(',')"
        :key="item"
        class="swipe-item"
      >
        <!-- <img :src="item" @click="preview(index)" /> -->
        <img :src="item" @click="previewFn(index)" />
      </van-swipe-item>
    </van-swipe>
    <!-- 组件的方式渲染图片预览 -->
    <!-- vue2和vue3父子组件同步 -->
    <van-image-preview
      v-model:show="show"
      :images="goodsDetail.banners[0].split(',')"
      :startPosition="startPosition"
      @change="onChange"
    >
      <template v-slot:index>第{{ index + 1 }}页</template>
    </van-image-preview>
    <!-- 商品详情信息 -->
    <div style="padding: 10px">
      <van-tag type="danger" size="large">自营</van-tag>
      <span v-text="goodsDetail.proname" style="margin-left: 10px"></span>
      <p style="color: red; font-weight: 900">
        ￥{{ formatPrice(goodsDetail.originprice) }}
      </p>
    </div>
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-action-bar-icon
        icon="cart-o"
        text="购物车"
        badge="5"
        @click="$router.replace('/cart')"
      />
      <van-action-bar-icon icon="shop-o" text="店铺" />
      <van-action-bar-button type="warning" text="加入购物车" @click="add" />
      <van-action-bar-button type="danger" text="立即购买" />
    </van-action-bar>
  </div>
</template>

<script setup>
import { showImagePreview } from 'vant'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getGoodsDetail } from '@/api/goods'
import { useCartStore } from '@/store/cart'

const route = useRoute()
const router = useRouter()
const store = useCartStore()

const goodsDetail = ref(null)
const show = ref(false)
const startPosition = ref(0)
const index = ref(0)

const onChange = newIndex => {
  index.value = newIndex
}

// 图片预览
const preview = index => {
  startPosition.value = index
  show.value = true
}

const previewFn = index => {
  showImagePreview({
    images: goodsDetail.value.banners[0].split(','),
    startPosition: index
  })
}

const getGoodsDetailData = async () => {
  const res = await getGoodsDetail(route.query.proid)
  goodsDetail.value = res.data
}

getGoodsDetailData()

const formatPrice = price => {
  return price.toFixed(2)
}

const onClickLeft = () => {
  router.back()
}

// 加入购物车
const add = () => {
  const goods = {
    proid: goodsDetail.value.proid,
    proname: goodsDetail.value.proname,
    img: goodsDetail.value.img1,
    price: goodsDetail.value.originprice,
    num: 1,
    checked: true
  }

  store.addToCart(goods)
}
</script>

<style lang="scss" scoped>
.swipe {
  width: 100%;
  height: 350px;
}
.swipe-item {
  width: 100%;
  height: 350px;
}
.swipe-item img {
  width: 100%;
  height: 100%;
}
</style>
